<template>
  <!-- 添加或编辑对话框 -->
  <el-dialog class="xiaobu-form-dialog" v-bind="$attrs" v-on="$listeners">
    <div v-hasPermi="['system:dictItem:update']" class="edit-box flex-c-e"
      v-show="baseForm.dictItemId && baseForm.isSystem === '0'">
      <el-button type="primary" class="edit" @click="toggleEdit">{{
        isEdit ? "取消编辑" : "编辑"
      }}</el-button>
    </div>
    <div class="el-dialog-body-child">
      <el-form class="clearfix" ref="dialogFormRef" :model="dialogForm" :rules="rules"
        :disabled="!!(!isEdit && baseForm.dictItemId)" label-width="120px">
        <el-form-item class="half" label=" " prop="parentDictItemId">
          <div class="content-label one-line five required">字典值父级</div>
          <div class="box flex-c-s">
            <el-cascader aria-hidden="false" :options="options" :props="props" disabled
              v-model="dialogForm.parentDictItemId" clearable placeholder="请选择字典值父级" />
          </div>
        </el-form-item>
        <el-form-item class="half" label="字典值" prop="dictValue">
          <el-input v-model.trim="dialogForm.dictValue" clearable placeholder="请输入字典值" />
        </el-form-item>
        <el-form-item class="half" label="字典值名称" prop="dictLabel">
          <el-input v-model.trim="dialogForm.dictLabel" clearable placeholder="请输入字典值名称" />
        </el-form-item>
        <el-form-item label=" " class="half" prop="elementType">
          <div class="content-label four">element-ui类型</div>
          <div class="box flex-c-s">
            <el-select-dict class="flex-grow" dictType="ELEMENT_UI_TYPE" v-model="dialogForm.elementType" clearable
              placeholder="请选择element-ui类型" />
            <el-tooltip class="item" effect="dark" content="设置此类型后，标签，按钮等组件的type可自动为此配置类型" placement="top">
              <i class="tips-icon el-icon-question"></i>
            </el-tooltip>
          </div>
        </el-form-item>
        <el-form-item label=" " class="half" prop="vantType">
          <div class="content-label four">vant-ui类型</div>
          <div class="box flex-c-s">
            <el-select-dict class="flex-grow" dictType="VANT_UI_TYPE" v-model="dialogForm.vantType" clearable
              placeholder="请选择vant-ui类型" />
            <el-tooltip class="item" effect="dark" content="设置此类型后，标签，按钮等组件的type可自动为此配置类型" placement="top">
              <i class="tips-icon el-icon-question"></i>
            </el-tooltip>
          </div>
        </el-form-item>
        <el-form-item label="颜色" class="half" prop="color">
          <div class="box flex-c-s">
            <el-color-picker v-model="dialogForm.color"></el-color-picker>
            <el-tooltip class="item" effect="dark" content="选择颜色后，标签或按钮等组件的color属性可自动配置为此颜色值" placement="top">
              <i class="tips-icon el-icon-question"></i>
            </el-tooltip>
          </div>
        </el-form-item>
        <el-form-item class="all" label="" prop="jsonstr">
          <div class="content-label five">额外的JSON字典数据</div>
          <el-input type="textarea" v-model.trim="dialogForm.jsonstr" :autosize="{ minRows: 5, maxRows: 8 }" clearable
            placeholder='请输入额外的JSON字典数据如：{"activeColor":"pink"}' />
        </el-form-item>
        <el-form-item class="all" label="备注" prop="remark">
          <el-input type="textarea" v-model="dialogForm.remark" :autosize="{ minRows: 5, maxRows: 8 }" clearable
            placeholder="请输入备注" />
        </el-form-item>
      </el-form>
    </div>
    <div slot="footer" class="dialog-footer">
      <template>
        <el-button @click="$emit('close')">{{
          !baseForm.configId || isEdit ? "取 消" : "关 闭"
        }}</el-button>
        <el-button type="primary" @click="submitForm" v-show="!baseForm.configId || isEdit">确 定</el-button>
      </template>
    </div>
  </el-dialog>
</template>
<script>
import { dictItemApi } from "@/api"
export default {
  name: "ConfigDialog",
  props: {
    // 是否是编辑
    isUpdate: {
      type: Boolean,
      default: false
    },
    // 配置数据
    baseForm: {
      type: Object,
      default: () => {
        return {}
      }
    },
    // 字典选项
    options: {
      type: Array,
      default: () => {
        return []
      }
    },
    props: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data() {
    /** 检查用户名是否已存在 */
    const checkDictValue = (rule, value, callback) => {
      const rex = /[A-Za-z0-9]+$/
      if (!rex.test(value)) {
        callback("字典代码只能为英文字母或数字组成！")
        return
      }
      dictItemApi
        .judgeExist({
          dictValue: value,
          dictItemId: this.baseForm.dictItemId,
          dictId: this.baseForm.dictId
        })
        .then((data) => {
          if (data.validateResult) {
            callback()
          } else {
            callback(data.msg)
          }
        })
    }

    const checkJsonstr = (rule, value, callback) => {
      if (!value) {
        callback()
        return
      }
      try {
        const data = JSON.parse(value)
        if (Object.prototype.toString.call(data) !== "[object Object]") {
          callback(`请输入正确的额外的JSON字符串`)
          return
        }
        callback()
      } catch (err) {
        callback(`请输入正确的额外的JSON字符串`)
        return
      }
    }
    return {
      isEdit: false, // 是否是在编辑
      dialogForm: {}, // 弹框表单
      // 表单校验
      rules: {
        dictLabel: [
          { required: true, message: "请输入字典名称", trigger: "blur" }
        ],
        dictValue: [
          { required: true, message: "请输入字典代码", trigger: "blur" },
          { validator: checkDictValue, trigger: "blur" }
        ],
        jsonstr: [{ validator: checkJsonstr, trigger: "blur" }]
      }
    }
  },
  watch: {
    isUpdate(val) {
      this.isEdit = val
    },
    // 监听baseForm变化 拷贝baseForm
    baseForm: {
      handler: function(val) {
        this.dialogForm = JSON.parse(JSON.stringify(val))
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    // 编辑或取消编辑
    toggleEdit() {
      if (!this.isEdit) {
        this.isEdit = true
        return
      }
      this.isEdit = false
      this.dialogForm = JSON.parse(JSON.stringify(this.baseForm))
    },
    // 重置表单
    resetForm() {
      this.isEdit = false
      this.$nextTick(() => {
        this.$refs.dialogFormRef.clearValidate()
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["dialogFormRef"].validate((valid) => {
        if (valid) {
          const params = JSON.parse(JSON.stringify(this.dialogForm))
          params.jsonstr = params.jsonstr
            ? JSON.stringify(JSON.parse(params.jsonstr))
            : ""

          // 更新
          if (params.dictItemId) {
            dictItemApi.updateItem(params).then((data) => {
              this.$modal.msgSuccess("修改字典值成功")
              this.$emit("close")
              this.$emit("successs")
            })
          } else {
            // 新增
            dictItemApi.createItem(params).then((data) => {
              this.$modal.msgSuccess("新增字典值成功")
              this.$emit("close")
              this.$emit("successs")
            })
          }
        }
      })
    }
  }
}
</script>
